package com.heima.seckill.controller;

import com.heima.seckill.pojo.User;
import com.heima.seckill.service.IGoodsService;
import com.heima.seckill.service.IUserService;
import com.heima.seckill.vo.DetailVo;
import com.heima.seckill.vo.GoodsVo;
import com.heima.seckill.vo.RespBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 *      * 本机 1000线程*10循环   pqs：925  异常率 0
 *         页面缓存优化后            qps：2066  异常率 0
 *      * 虚拟机 1000线程*10循环   pqs：168  异常率 0
 * 商品
 */
@Controller
@RequestMapping("/goods")
public class GoodsController {
    @Autowired
    private IUserService iUserService;
    @Autowired
    private IGoodsService goodsService;
    @Qualifier("JsonRedisTemplate")
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ThymeleafViewResolver thymeleafViewResolver;

    /**
     * 商品列表
     * @param model
     * @param user
     * @return
     */

    @RequestMapping(value = "/toList",produces = "text/html;charset=utf-8")
    @ResponseBody
    public String toList(Model model,User user,
                         HttpServletRequest request,HttpServletResponse response) {
        ValueOperations valueOperations = redisTemplate.opsForValue();
        String  html = (String) valueOperations.get("goodsList");//页面缓存
        if (!StringUtils.isEmpty(html)){ return html;}
        //如果为空，手动渲染， 存入Redis 并返回
        model.addAttribute("user",user);  //        if (user==null){return "login"; }
        model.addAttribute("goodsList",goodsService.findGoodsVo());
        WebContext context = new WebContext(request,response,request.getServletContext(),
                request.getLocale(),model.asMap());
        html= thymeleafViewResolver.getTemplateEngine().process("goodsList", context);
        if (!StringUtils.isEmpty(html)){
            valueOperations.set("goodsList",html,60, TimeUnit.SECONDS);
        }
        return html;
    }



    @RequestMapping(value = "/Detail2/{goodsId}",produces = "text/html;charset=utf-8")
    @ResponseBody
    public String Detail2(Model model, @PathVariable("goodsId")String goodsId,User user,
                         HttpServletRequest request,HttpServletResponse response) {
        ValueOperations valueOperations = redisTemplate.opsForValue();
        String  html = (String) valueOperations.get("goodsDetail:"+goodsId);//页面缓存
        if (!StringUtils.isEmpty(html)){ return html;}

        model.addAttribute("user",user);
        GoodsVo goodsVo= goodsService.findGoodsVoById(goodsId);
        Date startDate = goodsVo. getStartDate();
        Date endDate = goodsVo . getEndDate();
        Date nowDate = new Date() ;
        System.out.println("now:"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(nowDate)+"start:"+
                new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(startDate));
        //秒杀状态

        System.out.println("结束时间--->"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(goodsVo.getEndDate()));
        int secKillStatus = 0;
        //倒计时
        int remainSeconds=0;
        //秒杀还未开始
        if (nowDate . before (startDate)){
            remainSeconds= (int) ((startDate.getTime()-nowDate.getTime())/1000);
        }else if (nowDate . after ( endDate)){
            // 秒杀已结束
            secKillStatus = 2;
            remainSeconds=-1;
        }else{
            secKillStatus = 1;
            remainSeconds=0;
        }
        System.out.println(remainSeconds);
        model.addAttribute("remainSeconds",remainSeconds);
        model.addAttribute("secKillStatus",secKillStatus);
        model. addAttribute( "goods" , goodsVo);

        WebContext context = new WebContext(request,response,request.getServletContext(),
                request.getLocale(),model.asMap());
        html= thymeleafViewResolver.getTemplateEngine().process("goodsDetail", context);
        if (!StringUtils.isEmpty(html)){
            valueOperations.set("goodsDetail"+goodsId,html,60, TimeUnit.SECONDS);
        }
        return html;
    }


    @RequestMapping("/detail/{goodsId}")
    @ResponseBody
    public RespBean Detail(Model model, @PathVariable("goodsId")String goodsId, User user,
                           HttpServletRequest request, HttpServletResponse response) {
        GoodsVo goodsVo= goodsService.findGoodsVoById(goodsId);
        Date startDate = goodsVo. getStartDate();
        Date endDate = goodsVo . getEndDate();
        Date nowDate = new Date() ;
        System.out.println("now:"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(nowDate)+"start:"+
                new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(startDate));
            //秒杀状态

        System.out.println("结束时间--->"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(goodsVo.getEndDate()));
        int secKillStatus = 0;
        //倒计时
        int remainSeconds=0;
          //秒杀还未开始
        if (nowDate . before (startDate)){
            remainSeconds= (int) ((startDate.getTime()-nowDate.getTime())/1000);
        }else if (nowDate . after ( endDate)){
             // 秒杀已结束
            secKillStatus = 2;
            remainSeconds=-1;
        }else{
            secKillStatus = 1;
            remainSeconds=0;
        }
        DetailVo detailVo = new DetailVo(user, goodsVo, secKillStatus, remainSeconds);
        System.out.println(detailVo.getUser());
        return RespBean.success(detailVo);
    }



}
